import wxValidate from 'wechat-validate'
import { getcodelAPI } from '../../api/public'
import { loginAPI } from '../../api/public'
Page({
  // validate的混入
  behaviors:[wxValidate],
  data: {
    countDownVisible: false,
    mobile:'',
    code:'',
    // 跳回路由路径
    redirectURL:''
  },
  onLoad(query) {
    // console.log(query);
    this.setData({
      redirectURL:query.redirectURL
    })
    
  },
  rules: {
    mobile: [
      {required: true, message: '请填写手机号码!'},
      {pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!'}
    ],
    code: [
      {required: true, message: '请填写验证码!'},
      {pattern: /^\d{6}$/, message: '请填写正确的验证码!'}
    ]
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  async captcha() {
    // this.validate('mobile')传参代表监听这个表单验证，不传是全部
    const {valid,message} =  this.validate('mobile')
    // console.log(valid)
    const {mobile} = this.data
    if (!valid) {
      wx.utils.toast(message)
    }else{
      await getcodelAPI(mobile)
      // console.log(res);
      this.setData({
        countDownVisible: true
      })
    }
  },
  async submit() {
    // console.log(213);
    // console.log(getApp());
    const valid = this.validate()
    // console.log(valid);
    const {mobile,code} = this.data
    if (valid) {
      // console.log(123);
      try {
      // 调用登录接口
      const res = await loginAPI(mobile,code)
      console.log(res);
      // if (res.code !== 10000) {
      //   return wx.utils.toast('登录失败，稍后再试')
      // }
      // 记录登录状态
      getApp().tokenmethod('token',res.data.token)
      getApp().tokenmethod('refreshToken',res.data.refreshToken)
      // 重定向
      wx.redirectTo({
        url:this.data.redirectURL
      })
      } catch (error) {
        // console.log(error);
      }
    }
    
  }
})
